import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

import '../../../../pojo/ImPojo.dart';
import '../../../../util/DateUtil.dart';
import '../../../../util/ImConstant.dart';
import '../../../bloc/SessionListCubit.dart';
import '../SessionIconView.dart';
import '../pane/RichTextMessagePane.dart';

class SessionItemView extends StatelessWidget {

  final _logger = Logger(printer: PrettyPrinter(),);

  final ImSession imSession;

  SessionItemView({required this.imSession, super.key});

  final _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return ListTile(
      // dense: true,
      key: _key,
      leading: SessionIconView(session: imSession),
      title: Text('${imSession.name}',
          style: const TextStyle(fontSize: ImConstant.IM_DEFAULT_SIZE, fontWeight: FontWeight.w500)),
      subtitle: SessionMessagePane(message: imSession.latelyMessage??'', maxLines: 1,),
      trailing: Text('${DateUtil.sessionShowTime(imSession.updateTime)}', style: const TextStyle(fontSize: 9),),
      onTap: (){
        _showSendMessage(context, imSession);
      },
      onLongPress: ()=> _showPopup(context, imSession!),
    );
  }

  void _showSendMessage(BuildContext context, ImSession imSession) {
    _logger.i("show session: ${imSession?.id}");
    Navigator.of(context).pushNamedAndRemoveUntil("/MessageSendPage", ModalRoute.withName('/MainPage'),
        arguments: {"id": imSession?.id!, "name": imSession?.name});
  }

  void _showPopup(BuildContext context, ImSession imSession) {
    RenderBox? renderBox = _key.currentContext!.findRenderObject() as RenderBox?;
    var offset = renderBox?.localToGlobal(Offset.zero);
    var size = renderBox?.size;
    var w = size?.width??0/2;

    var text = "置顶该聊天";
    bool isTop = true;
    if (imSession.groupCode != null) {
      isTop = !(imSession.group?.currentGroupUser?.isTop??false);
    } else {
      if (imSession.isTop && imSession.fromUserId!.compareTo(imSession.toUserId!) >= 0) {
        text = "取消置顶";
        isTop = false;
      } else if (imSession.isTop2 && imSession.fromUserId!.compareTo(imSession.toUserId!) < 0) {
        text = "取消置顶";
        isTop = false;
      }
    }

    showMenu(context: context,
        position: RelativeRect.fromLTRB(offset!.dx + w - 300, offset!.dy, w-200, 0),
        items: [PopupMenuItem(onTap: () { sessionTopEvent(context, isTop); }, child: Text(text), ),
          PopupMenuItem(onTap: (){ sessionHide(context); }, child: const Text('不显示该聊天'), ),
          PopupMenuItem(onTap: (){ sessionDelete(context); }, child: const Text('删除该聊天'), )]);
  }

  void sessionTopEvent(BuildContext context, bool isTop) {
    var sessionListCubit = Provider.of<SessionListCubit>(context, listen: false);
    sessionListCubit.sessionTop(imSession, isTop);
  }

  void sessionHide(BuildContext context) {
    showDialog(context: context,
        builder: (context) {
          return AlertDialog(title: const Text('提醒', style: TextStyle(color: Colors.blueAccent)),
              content: const Text('是否确实不显示？'),
              actions: <Widget>[
                TextButton(child: const Text("确定"), onPressed: () {
                  var sessionListCubit = Provider.of<SessionListCubit>(context, listen: false);
                  sessionListCubit.hideSession(imSession);
                  Navigator.of(context).pop();
                }),
                TextButton(child: const Text("取消"), onPressed: () => Navigator.of(context).pop())
              ]);
        });
  }

  void sessionDelete(BuildContext context) {
    showDialog(context: context,
        builder: (context) {
          return AlertDialog(title: const Text('提醒', style: TextStyle(color: Colors.blueAccent)),
              content: const Text('是否删除本聊天（删除本聊天相关所有内容）？'),
              actions: <Widget>[
                TextButton(child: const Text("确定"), onPressed: () {
                  var sessionListCubit = Provider.of<SessionListCubit>(context, listen: false);
                  sessionListCubit.deleteSession(imSession);
                  Navigator.of(context).pop();
                }),
                TextButton(child: const Text("取消"), onPressed: () => Navigator.of(context).pop())
              ]);
        });
  }

}